import storage from 'store'
import expirePlugin from 'store/plugins/expire'
import { getInfo, login, logout } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'

storage.addPlugin(expirePlugin)
const user = {
  namespace: true,
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  },
  
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },
  
  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          if (response.code === 200) {
            const result = response.data
            storage.set(ACCESS_TOKEN, result.token, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
            commit('SET_TOKEN', result.token)
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    
    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        // 请求后端获取用户信息 /api/user/info
        getInfo().then(response => {
          const { data } = response
          // 构造数据
          if (data.role && data.permissions.length > 0) {
            const role = { ...data.role }
            role.permissions = data.permissions.map(permission => {
              return {
                ...permission,
                actionList: [{ 'actionId': 1, 'action': 'add', 'remark': '新增' }, { 'actionId': 2, 'action': 'query', 'remark': '查询' }, { 'actionId': 3, 'action': 'get', 'remark': '详情' }, { 'actionId': 4, 'action': 'update', 'remark': '修改' }, { 'actionId': 5, 'action': 'delete', 'remark': '删除' }]
              }
            })
            role.permissionList = role.permissions.map(permission => {
              return permission.permission
            })
            // 覆盖响应体的 role, 供下游使用
            data.role = role
            commit('SET_ROLES', role)
            commit('SET_INFO', data.userInfo)
            commit('SET_NAME', { name: data.userInfo.nickName, welcome: welcome() })
            commit('SET_AVATAR', data.userInfo.avatar)
            // 将数据放到下游
            resolve(data)
          } else {
            reject(new Error('roles必须为非空数组'))
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    
    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          storage.remove(ACCESS_TOKEN)
          resolve()
        }).catch((err) => {
          console.log('退出失败', err)
          // resolve()
        }).finally(() => {
        })
      })
    }
    
  }
}

export default user
